<template>
  <div class="users-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索框与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            :clearable="true"
            @clear="getUsersList"
          >
            <el-button icon="el-icon-search" slot="append" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="usersList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="用户"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 用于插槽的使用方式 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="操作" min-width="100px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showAllotRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <!-- page-sizes表示每一页显示多少条数据 page-size表示组件显示的页码个数 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框区域 -->
    <el-dialog title="添加用户信息" :visible.sync="addDialogVisible" width="30%" @close="resetForm">
      <!-- 内容的主体区域 -->
      <el-form :model="addForm" :rules="addFormRule" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="addUser">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框区域 -->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editdialogClosed"
    >
      <!-- 内容的主体区域 (表单) -->
      <el-form :model="editForm" :rules="editFormRule" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="editUserInfo">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="allotRoleDialogVisible"
      width="50%"
      @closed="allotRoleDialogClosed"
    >
      <div>
        <p>当前用户角色： {{ userInfo.username }}</p>
        <p>当前用户角色： {{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allotRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //表单的自定义校验规则
    // email验证规则
    var checkEmail = (rule, value, cb) => {
      //正则表达式
      var reg = new RegExp(
        '^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$'
      )
      var valid = reg.test(value)
      if (!valid) return cb(new Error('邮箱格式错误,请重新输入邮箱'))
      return cb()
    }
    var checkMobile = (rule, value, cb) => {
      var reg = new RegExp('^1[3|4|5|7|8][0-9]{9}$')
      var valid = reg.test(value)
      if (!valid) return cb(new Error('手机号错误,请重新输入手机号'))
      return cb()
    }
    return {
      // 发起请求的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户信息
      usersList: [],
      // 数据总数
      total: 0,
      // 添加用户 控制对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户 对话框表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户 表单数据的验证规则
      addFormRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },

      // 编辑用户 控制对话框的显示与隐藏
      editDialogVisible: false,
      // 添加用户 对话框表单数据
      editForm: {},
      editFormRule: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      allotRoleDialogVisible: false,
      // 当前要分配角色用户的信息
      userInfo: {},
      // 所有的角色列表
      rolesList: [],
      // 选择框中选中的值
      selectedId: ''
    }
  },
  methods: {
    // 获取数据
    async getUsersList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.usersList = res.data.users
      this.total = res.data.total
    },

    // 对分页组件进行操作
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // val是获取最新的值
      // 改变pagesize
      this.queryInfo.pagesize = val
      console.log(val)
      this.getUsersList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      // 当前页码改变
      this.queryInfo.pagenum = val
      this.getUsersList()
    },
    // 改变用户状态
    async changeUserState(userInfo) {
      // console.log(userInfo)
      const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('更新状态成功')
      this.getUsersList()
    },

    // 添加用户方法
    // 重置表单
    resetForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async value => {
        if (!value) return
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        this.addDialogVisible = false
        this.getUsersList()
        // console.log(value)
      })
    },
    // 编辑用户信息方法
    async showEditDialog(userId) {
      const { data: res } = await this.$http.get(`users/${userId}`)
      if (res.meta.status !== 200) return this.$message.error('res.meta.msg')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editdialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    editUserInfo() {
      //同理开始预校验
      this.$refs.editFormRef.validate(async value => {
        if (!value) return
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('res.meta.msg')
        // 更新成功
        this.editDialogVisible = false
        this.getUsersList()

        console.log(res)
      })
    },
    // 删除用户方法
    async removeUserById(userId) {
      // 首先来个messageBox进行提时
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'cancel') return this.$message.info('已取消删除')
      if (confirmResult === 'confirm') {
        this.$message.success('已确认删除')
        const { data: res } = await this.$http.delete(`users/${userId}`)
        if (res.meta.status !== 200) return this.$http.error('res.meta.msg')
        // 删除成功
        this.getUsersList()
      }
    },
    // 显示分配角色对话框
    async showAllotRoleDialog(userInfo) {
      this.userInfo = userInfo

      // 在展示对话框之前，获取所有的角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.allotRoleDialogVisible = true
    },
    // 保存用户角色
    async saveRoleInfo() {
      if (!this.selectedId) {
        return this.$message.info('请选择需要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('设置角色失败')
      }
      this.$message.success('设置角色成功')
      this.getUsersList()
      this.allotRoleDialogVisible = false
    },
    // 监听设置角色对话框的关闭
    allotRoleDialogClosed() {
      this.selectedId = ''
      this.userinfo = {}
    }
  },
  created() {
    this.getUsersList()
  }
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
